package com.ruixun.controller;

import com.ruixun.common.PageData;
import com.ruixun.common.ResponseResult;
import com.ruixun.entity.User;
import com.ruixun.query.UserPageQuery;
import com.ruixun.rvo.UserRvo;
import com.ruixun.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户管理控制器
 * @author ruixun
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    @PostMapping("/login")
    public ResponseResult<PageData<UserRvo>> getPage(@Valid @RequestBody UserPageQuery userPageQuery) {
        PageData<UserRvo> pageData = userService.getPage(userPageQuery);
        return ResponseResult.success(pageData);
    }

    @ApiOperation(value = "分页查询用户列表", notes = "支持按用户名模糊查询和年龄等值查询")
    @PostMapping("/page")
    public ResponseResult<PageData<UserRvo>> getUserPage(@Valid @RequestBody UserPageQuery userPageQuery) {
        PageData<UserRvo> pageData = userService.getPage(userPageQuery);
        return ResponseResult.success(pageData);
    }

    @ApiOperation(value = "新增用户", notes = "新增用户信息")
    @PostMapping("/add")
    public ResponseResult<Boolean> addUser(@Valid @RequestBody User user) {
        boolean result = userService.addUser(user);
        return result ? ResponseResult.success(true) : ResponseResult.fail("新增用户失败");
    }

    @ApiOperation(value = "修改用户", notes = "修改用户信息")
    @PostMapping("/update")
    public ResponseResult<Boolean> updateUser(@Valid @RequestBody User user) {
        if (user.getId() == null) {
            return ResponseResult.fail("用户ID不能为空");
        }
        boolean result = userService.updateUser(user);
        return result ? ResponseResult.success(true) : ResponseResult.fail("修改用户失败");
    }

    @ApiOperation(value = "删除用户", notes = "根据ID删除用户（逻辑删除）")
    @PostMapping("/delete/{id}")
    public ResponseResult<Boolean> deleteUser(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        boolean result = userService.deleteUser(id);
        return result ? ResponseResult.success(true) : ResponseResult.fail("删除用户失败");
    }

    @ApiOperation(value = "获取用户详情", notes = "根据ID获取用户详细信息")
    @GetMapping("/detail/{id}")
    public ResponseResult<UserRvo> getUserDetail(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        UserRvo user = userService.getUserById(id);
        return user != null ? ResponseResult.success(user) : ResponseResult.fail("用户不存在");
    }

}